#!/bin/bash

# 获取所有ros2相关进程的PID，排除grep命令本身和脚本自身的进程
pids=$(ps aux | grep -i ros2 | grep -v grep | grep -v "$0" | awk '{print $2}')

# 检查是否找到了任何进程
if [ -z "$pids" ]; then
    echo "No ROS2 processes found to kill."
    exit 0
fi

# 首先尝试使用SIGTERM信号优雅地终止进程
echo "Sending SIGTERM to ROS2 processes: $pids"
kill -15 $pids 2>/dev/null

# 等待几秒让进程处理终止信号
sleep 2

# 检查是否还有进程存活，如果有则强制杀死
remaining_pids=$(ps aux | grep -i ros2 | grep -v grep | grep -v "$0" | awk '{print $2}')
if [ -n "$remaining_pids" ]; then
    echo "Some processes did not terminate gracefully. Force killing with SIGKILL: $remaining_pids"
    kill -9 $remaining_pids 2>/dev/null
fi

echo "All ROS2 processes have been terminated."